package io.finer.erp.jeecg.bas.service.impl;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.MaterialConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;

import cn.hutool.core.util.NumberUtil;
import io.finer.erp.jeecg.bas.dto.ZrkOrderProductDTO;
import io.finer.erp.jeecg.bas.dto.ZrkShopCustomerDTO;
import io.finer.erp.jeecg.bas.dto.ZrkShopOrderDTO;
import io.finer.erp.jeecg.bas.dto.ZrkShopTotalDTO;
import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasPfMaterial;
import io.finer.erp.jeecg.bas.entity.BasProportion;
import io.finer.erp.jeecg.bas.entity.ZrkOrderProduct;
import io.finer.erp.jeecg.bas.entity.ZrkShoporder;
import io.finer.erp.jeecg.bas.entity.ZzDeviceType;
import io.finer.erp.jeecg.bas.entity.ZzShoporder;
import io.finer.erp.jeecg.bas.mapper.BasCustomerMapper;
import io.finer.erp.jeecg.bas.mapper.BasMaterialCategoryMapper;
import io.finer.erp.jeecg.bas.mapper.ZrkOrderProductMapper;
import io.finer.erp.jeecg.bas.mapper.ZrkShoporderMapper;
import io.finer.erp.jeecg.bas.mapper.ZzDeviceTypeMapper;
import io.finer.erp.jeecg.bas.mapper.ZzShoporderMapper;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasPfMaterialService;
import io.finer.erp.jeecg.bas.service.IBasProportionService;
import io.finer.erp.jeecg.bas.service.IZrkShoporderService;
import io.finer.erp.jeecg.bas.service.IZzShoporderService;
import io.finer.erp.jeecg.bas.vo.CreateZzOrderVO;
import io.finer.erp.jeecg.bas.vo.OrderVO;
import io.finer.erp.jeecg.bas.vo.ShopTotalVO;
import io.finer.erp.jeecg.stock.entity.StkInventory;
import io.finer.erp.jeecg.stock.service.IStkInventoryService;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 商城订单信息表
 * @Author: jeecg-boot
 * @Date:   2020-08-22
 * @Version: V1.0
 */
@Service
@Slf4j
public class ZrkShoporderServiceImpl extends ServiceImpl<ZrkShoporderMapper, ZrkShoporder> implements IZrkShoporderService {

	@Autowired
	private ZrkShoporderMapper zrkShoporderMapper;
	@Autowired
	private ZrkOrderProductMapper zrkOrderProductMapper;
	@Autowired
	private IBasMaterialCategoryService categoryService;
	@Autowired
	private IZzShoporderService zzShoporderService;
	@Autowired
	private IStkInventoryService stkInventoryService;
	@Autowired
	private IBasMaterialService basMaterialService;
	@Autowired
	private IBasPfMaterialService pfMaterialService;
	@Autowired
	private IBasProportionService basProportionService;
	@Autowired
	private ISysBaseAPI baseApi;
	@Autowired
	private BasCustomerMapper basCustomerMapper;
	@Autowired
	private ZzDeviceTypeMapper zzDeviceTypeMapper;
	@Autowired
	private ISysBaseAPI iSysBaseAPI;
	@Autowired
	private BasMaterialCategoryMapper basMaterialCategoryMapper;
	@Autowired
	private ZzShoporderMapper zzShoporderMapper;

	@Override
	@Transactional
	public void saveMain(ZrkShoporder zrkShoporder, ZrkOrderProduct zrkOrderProduct) {
		zrkShoporderMapper.insert(zrkShoporder);
		//外键设置
		zrkOrderProduct.setOrderNo(zrkShoporder.getShopOrder());
		zrkOrderProduct.setOrderId(zrkShoporder.getId());
		String categoryId = zrkOrderProduct.getMaterialId();
		BasMaterialCategory category = categoryService.getById(categoryId);
		zrkOrderProduct.setProductName(category.getName());
		zrkOrderProduct.setUnitId(category.getUnitId());
		if (StringUtils.equals("40288101710a4c6201710a6618cc0003", category.getUnitId())) {
			if (zrkOrderProduct.getProductCount() != null && zrkOrderProduct.getUnitPrice() != null) {
				zrkOrderProduct.setTotalPrice(zrkOrderProduct.getProductCount().multiply(zrkOrderProduct.getUnitPrice()));
			}
		}
		if (StringUtils.equals("40288101710a4c6201710a65913d0002", category.getUnitId())) {
			if (zrkOrderProduct.getProductCount() != null && zrkOrderProduct.getUnitPrice() != null) {
				zrkOrderProduct.setTotalPrice(zrkOrderProduct.getProductCount().multiply(zrkOrderProduct.getUnitPrice()));
			}
		}
		zrkOrderProduct.setId(zrkShoporder.getId());
		zrkOrderProductMapper.insert(zrkOrderProduct);
	}

	@Override
	@Transactional
	public void updateMain(ZrkShoporder zrkShoporder, ZrkOrderProduct zrkOrderProduct) {
		zrkShoporderMapper.updateById(zrkShoporder);

		//1.先删除子表数据
		zrkOrderProductMapper.deleteByMainId(zrkShoporder.getId());

		//外键设置
		zrkOrderProduct.setOrderNo(zrkShoporder.getShopOrder());
		zrkOrderProduct.setOrderId(zrkShoporder.getId());
		String categoryId = zrkOrderProduct.getMaterialId();
		BasMaterialCategory category = categoryService.getById(categoryId);
		String productName = "";
		String unitId = "";
		if (category != null) {
			productName = category.getName();
			unitId = category.getUnitId();
		}
		zrkOrderProduct.setProductName(productName);
		zrkOrderProduct.setUnitId(unitId);
		if (StringUtils.equals("40288101710a4c6201710a6618cc0003", category.getUnitId())) {
			if (zrkOrderProduct.getProductCount() != null && zrkOrderProduct.getUnitPrice() != null) {
				zrkOrderProduct.setTotalPrice(zrkOrderProduct.getProductCount().multiply(zrkOrderProduct.getUnitPrice()));
			}
		}
		if (StringUtils.equals("40288101710a4c6201710a65913d0002", category.getUnitId())) {
			if (zrkOrderProduct.getProductCount() != null && zrkOrderProduct.getUnitPrice() != null) {
				zrkOrderProduct.setTotalPrice(zrkOrderProduct.getProductCount().multiply(zrkOrderProduct.getUnitPrice()));
			}
		}
		zrkOrderProductMapper.insert(zrkOrderProduct);
	}

	@Override
	@Transactional
	public void delMain(String id) {
		zrkOrderProductMapper.deleteByMainId(id);
		zrkShoporderMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			zrkOrderProductMapper.deleteByMainId(id.toString());
			zrkShoporderMapper.deleteById(id);
		}
	}

	@Override
	public ZrkShoporder selectByActiveDayPlan() {
		return zrkShoporderMapper.selectByActiveDayPlan();
	}

	@Override
	public ZrkShoporder selectByActiveMonthPlan() {
		return zrkShoporderMapper.selectByActiveMonthPlan();
	}

	@Override
	public ZrkShoporder selectByActiveYearPlan() {
		return zrkShoporderMapper.selectByActiveYearPlan();
	}

	@Override
	public ZrkShoporder selectNewOrOldCustomer(String customerId) {
		return zrkShoporderMapper.selectNewOrOldCustomer(customerId);
	}

	@Override
	public ZrkShoporder selectByOrderCode(String orderNo) {
		List<ZrkShoporder> list = lambdaQuery().eq(ZrkShoporder::getOrderNo, orderNo).list();
		if(null != list && 0 != list.size()) {
			return list.get(0);
		}
		return null;
	}
	
	@Transactional
	public Result<?> saveOrder(ZrkShoporder zrkShoporder, ZrkOrderProduct zrkOrderProduct){
		if(StringUtils.isBlank(zrkShoporder.getId())) {
			String billNo = baseApi.getNoByCode("shop_order_erp_no");
			zrkShoporder.setOrderNo(billNo);
			this.saveMain(zrkShoporder, zrkOrderProduct);
			return Result.ok("保存成功");
		} else {
			List<ZzShoporder> shoporderList = zzShoporderService.selectOrderByOrderNo(zrkShoporder.getOrderNo());
			if(shoporderList!=null&&shoporderList.size()>0) {
				for(ZzShoporder zzShopoder:shoporderList) {
					if(zzShopoder.getWoStatus()>1&&zzShopoder.getWoStatus()!=5) {
						throw new RuntimeException("车间任务单已被接单！");
					}
				}
			}
			this.updateMain(zrkShoporder, zrkOrderProduct);
			return Result.ok("修改成功。");
		}
	}

	@Override
	@Transactional
	public Result<?> addOrder(OrderVO orderVo) {
		ZrkShoporder zrkShoporder = null;
		ZrkOrderProduct zrkOrderProduct = null;
		if (StringUtils.isBlank(orderVo.getId())) {//订单id为空则为新增
			zrkShoporder = new ZrkShoporder(orderVo);
			zrkOrderProduct = new ZrkOrderProduct(orderVo);
		} else {//订单id不为空则为编辑
			zrkShoporder = this.getById(orderVo.getId());
			zrkOrderProduct = zrkOrderProductMapper.selectById(orderVo.getId());
		}
		BeanUtils.copyProperties(orderVo, zrkShoporder);
		BeanUtils.copyProperties(orderVo, zrkOrderProduct);
		zrkOrderProduct.setRemark(orderVo.getLabelRemarks());
		if (StringUtils.isBlank(zrkShoporder.getCustomerId())) {
			throw new RuntimeException("请选择客户！");
		}
		if (StringUtils.equals(MaterialConstant.PROCESS_COMPOUND, zrkOrderProduct.getProcessId())) {
			verifyInventory(zrkOrderProduct.getProductSpecs(), zrkOrderProduct.getProductCount(), zrkOrderProduct.getFormularId());
		}
		BigDecimal totalPrice = BigDecimal.ZERO;
		BigDecimal unitPrice = zrkOrderProduct.getUnitPrice();
		BigDecimal number = zrkOrderProduct.getProductCount();
		String modal = zrkOrderProduct.getProductSpecs();
		if (StringUtils.isNotBlank(modal)) {
			BigDecimal orderProductPrice = null;
			String[] strs = StringUtils.split(modal, "*");
			boolean flag = false;
			if (strs.length == 1) {
				flag = true;
			} else {
				String str1 = strs[0];
				String str2 = strs[1];
				boolean isNumberFlag = false;
				if (isNumber(str1) && isNumber(str2)) {
					isNumberFlag = true;
				}
				if (isNumberFlag && null != unitPrice) {
					BigDecimal num1 = new BigDecimal(str1);
					BigDecimal num2 = new BigDecimal(str2);
					BigDecimal big = new BigDecimal("0");
					if (num1.compareTo(big) > 0 || num2.compareTo(big) > 0) {
						BigDecimal w = num1.divide(new BigDecimal("100"), 4, BigDecimal.ROUND_DOWN);
						orderProductPrice = w.multiply(num2).multiply(number).multiply(unitPrice);
					} else {
						BigDecimal w = num1.divide(new BigDecimal("100"), 4, BigDecimal.ROUND_DOWN);
						BigDecimal l = num2.divide(new BigDecimal("100"), 4, BigDecimal.ROUND_DOWN);
						orderProductPrice = w.multiply(l).multiply(number).multiply(unitPrice);
					}
				} else {
					flag = true;
				}
			}
			if (flag && null != unitPrice) {
				orderProductPrice = unitPrice.multiply(number);
			}
			if (null != orderProductPrice) {
				orderProductPrice.setScale(2, BigDecimal.ROUND_DOWN);
				zrkOrderProduct.setTotalPrice(orderProductPrice);
				if ("1".equals(zrkOrderProduct.getProductType())) {
					totalPrice = totalPrice.add(orderProductPrice);
				}
			}
		}
		totalPrice = totalPrice.setScale(2, BigDecimal.ROUND_DOWN);
		zrkShoporder.setOrderMoney(totalPrice);
		BasCustomer basCustomer = basCustomerMapper.selectById(zrkShoporder.getCustomerId());
		zrkShoporder.setCustomerName(basCustomer.getName());
		zrkOrderProduct.setOutCount(BigDecimal.ZERO);
		return this.saveOrder(zrkShoporder, zrkOrderProduct);
	}
	
	public List<StkInventory> getInventoryByCategory(String categoryId, String dmz) {
		List<String> ids = this.basMaterialService.getInvenMaterialIdsByCateId(categoryId);
		LambdaQueryWrapper<StkInventory> query = new LambdaQueryWrapper<>();
		if(ids==null || ids.size()==0) {
			if(StringUtils.equals("1", dmz)) {
				throw new RuntimeException("底纸库存不足，请补充该底纸库存");
			}
			if(StringUtils.equals("2", dmz)) {
				throw new RuntimeException("面纸库存不足，请补充该面纸库存");
			}
		}
		query.in(StkInventory::getMaterialId, ids);
		query.gt(StkInventory::getQty, 0);
		return stkInventoryService.list(query);
	}
	
	private boolean isNumber(String number) {
		int index = number.indexOf(".");
		if (index < 0) {
			return StringUtils.isNumeric(number);
		} else {
			String num1 = number.substring(0, index);
			String num2 = number.substring(index + 1);

			return StringUtils.isNumeric(num1) && StringUtils.isNumeric(num2);
		}
	}
	
	public static void main(String[] args) {
		String number = "123";
		int index = number.indexOf(".");
		if (index < 0) {
			System.out.println(StringUtils.isNumeric(number));;
		} else {
			String num1 = number.substring(0, index);
			String num2 = number.substring(index + 1);
			System.out.println(StringUtils.isNumeric(num1) && StringUtils.isNumeric(num2));
			return ;
		}
	}

	@Override
	@Transactional
	public  Result<?> recallOrder(String id){
		ZrkShoporder zrkShoporder = this.getById(id);
		if(zrkShoporder==null) {
			return Result.error("未找到订单");
		}
		if(StringUtils.equals(zrkShoporder.getDelFlag(), "1")) {
			return Result.error("该订单已作废，无需撤回");
		}
		List<ZzShoporder> zzShoporder = zzShoporderService.selectOrderByOrderNo(zrkShoporder.getOrderNo());
		if (zzShoporder != null && zzShoporder.size() > 0) {
			for (ZzShoporder shoporder : zzShoporder) {
				if (shoporder.getWoStatus().equals(1)) {
					zzShoporderService.removeById(shoporder.getId());
				}else{
					throw new RuntimeException("撤回失败！任务单已派发。");
				}
			}
		} else {
			return Result.error("未找到任务单，无需撤回");
		}
		zrkShoporder.setIsPush("0");
		this.updateById(zrkShoporder);
		return Result.ok("撤回成功");
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<?> delOrder(String id) {
		ZrkShoporder zrkShoporder = this.getById(id);
		if(zrkShoporder==null) {
			return Result.error("作废失败，未找到订单");
		}
		if(StringUtils.equals(zrkShoporder.getDelFlag(), "1")) {
			return Result.error("该订单已作废，无需重复作废");
		}
		List<ZzShoporder> zzShoporder = zzShoporderService.selectOrderByOrderNo(zrkShoporder.getOrderNo());
		if (zzShoporder != null && zzShoporder.size() > 0) {
			for (ZzShoporder shoporder : zzShoporder) {
				if (shoporder.getWoStatus().equals(1)) {
					zzShoporderService.removeById(shoporder.getId());
				}else{
					return Result.error("作废失败！任务单已派发。");
				}
			}
		}
		zrkShoporder.setDelFlag("1");
		this.updateById(zrkShoporder);
		return Result.ok("作废成功");
	}

	@Override
	public Page<ZrkShopCustomerDTO> getCustomerAndProduct(IPage<ZrkShopCustomerDTO> page,String customerName) {
		return this.baseMapper.selectCustomerAndProduct(page,customerName);
	}

	@Override
	public Page<ZrkShopTotalDTO> getShopTotal(Page<ZrkShopTotalDTO> page, String customerName,@Param("orderTimeBegin") String orderTimeBegin,@Param("orderTimeEnd") String orderTimeEnd) {
		// TODO Auto-generated method stub
		List<ShopTotalVO> list = this.baseMapper.queryShopTotal(customerName,orderTimeBegin,orderTimeEnd);
		Map<String,ZrkShopTotalDTO> totalMap = Maps.newHashMap();
		if(list!=null&&list.size()>0) {
			for(ShopTotalVO shopTotalVO:list) {
				ZrkShopTotalDTO dto = totalMap.get(shopTotalVO.getMaterialId());
				if(dto==null) {
					dto = new ZrkShopTotalDTO();
					dto.setCustomerName(shopTotalVO.getCustomerName());
					dto.setProductName(shopTotalVO.getProductName());
					if(oConvertUtils.isEmpty(shopTotalVO.getTotalPrice())) {
						dto.setTotalPrice(new BigDecimal("0").toString());
					}else {
						dto.setTotalPrice(shopTotalVO.getTotalPrice().toString());
					}
					if(oConvertUtils.isNotEmpty(shopTotalVO.getModal())) {
						String[] modal = shopTotalVO.getModal().split("\\*");
						String width = "0";
						String length = "0";
						if(modal!=null&&modal.length>1) {
							if(oConvertUtils.isNotEmpty(modal[0])) {
								if(NumberUtil.isNumber(modal[0])) {
									width = modal[0];
								}
							}
							if(oConvertUtils.isNotEmpty(modal[1])) {
								if(NumberUtil.isNumber(modal[1])) {
									length = modal[1];
								}
							}
							BigDecimal productCount = BigDecimal.ZERO;
							if(oConvertUtils.isNotEmpty(shopTotalVO.getProductCount())) {
								productCount = shopTotalVO.getProductCount();
							}
							BigDecimal square = BigDecimal.ZERO;
							square = new BigDecimal(width).divide(new BigDecimal("100"), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(length)).multiply(productCount);
							dto.setTotalSquare(square.setScale(4,BigDecimal.ROUND_HALF_UP).toString());
						}
					}
					totalMap.put(shopTotalVO.getMaterialId(), dto);
				}else {
					if(oConvertUtils.isNotEmpty(shopTotalVO.getModal())) {
						String[] modal = shopTotalVO.getModal().split("\\*");
						String width = "0";
						String length = "0";
						if(modal!=null&&modal.length>1) {
							if(oConvertUtils.isNotEmpty(modal[0])) {
								if(NumberUtil.isNumber(modal[0])) {
									width = modal[0];
								}
							}
							if(oConvertUtils.isNotEmpty(modal[1])) {
								if(NumberUtil.isNumber(modal[1])) {
									length = modal[1];
								}
							}
							BigDecimal productCount = BigDecimal.ZERO;
							if(oConvertUtils.isNotEmpty(shopTotalVO.getProductCount())) {
								productCount = shopTotalVO.getProductCount();
							}
							BigDecimal square = BigDecimal.ZERO;
							square = new BigDecimal(width).divide(new BigDecimal("100"), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(length)).multiply(productCount);
							String talSquare = "0";
							if(oConvertUtils.isNotEmpty(dto.getTotalSquare())) {
								talSquare = dto.getTotalSquare();
							}
							BigDecimal totalSquare = new BigDecimal(talSquare).add(square);
							dto.setTotalSquare(totalSquare.setScale(4,BigDecimal.ROUND_HALF_UP).toString());
						}
						
					}
					BigDecimal price = new BigDecimal("0");
					if(oConvertUtils.isNotEmpty(shopTotalVO.getTotalPrice())){
						price = shopTotalVO.getTotalPrice();
					}
					BigDecimal totalPrice = new BigDecimal(dto.getTotalPrice()).add(price);
					dto.setTotalPrice(totalPrice.toString());
					totalMap.put(shopTotalVO.getMaterialId(), dto);
				}
			}
			List<ZrkShopTotalDTO> dtoList = new LinkedList<ZrkShopTotalDTO>();
			Collection<ZrkShopTotalDTO> values =  totalMap.values();
			Iterator<ZrkShopTotalDTO> it = values.iterator();
			while(it.hasNext()) {
				dtoList.add(it.next());
			}
			Page<ZrkShopTotalDTO> pageList = page.setRecords(dtoList);
			return pageList;
		}
		List<ZrkShopTotalDTO> dtoList = new LinkedList<ZrkShopTotalDTO>();
		return page.setRecords(dtoList);
	}

	@Override
	public Page<ZrkOrderProductDTO> querySalesVolumeByUser(Page<ZrkOrderProductDTO> page,String[] createBy, String orderTimeBegin, String orderTimeEnd) {
		// TODO Auto-generated method stub
		List<ZrkOrderProductDTO> dtoList = baseMapper.querySalesVolumeByUser(createBy, orderTimeBegin, orderTimeEnd);
		Map<String,ZrkOrderProductDTO> map = Maps.newHashMap();
		if(dtoList!=null && dtoList.size()>0) {
			for(ZrkOrderProductDTO zrkOrderProductDTO:dtoList) {
				if(zrkOrderProductDTO!=null && oConvertUtils.isNotEmpty(zrkOrderProductDTO.getCreateBy())) {
					ZrkOrderProductDTO dto = map.get(zrkOrderProductDTO.getCreateBy());
					if(dto==null) {
						dto = new ZrkOrderProductDTO();
						dto.setCreateBy(zrkOrderProductDTO.getCreateBy());
						BigDecimal totalPrice = zrkOrderProductDTO.getTotalPrice();
						if(oConvertUtils.isEmpty(totalPrice)) {
							totalPrice = BigDecimal.ZERO;
						}
						dto.setTotalPrice(zrkOrderProductDTO.getTotalPrice());
						if(oConvertUtils.isNotEmpty(zrkOrderProductDTO.getCreateBy())) {
							map.put(zrkOrderProductDTO.getCreateBy(), dto);
						}
					}else {
						dto.setCreateBy(zrkOrderProductDTO.getCreateBy());
						BigDecimal price = zrkOrderProductDTO.getTotalPrice();
						if(oConvertUtils.isEmpty(price)) {
							price = BigDecimal.ZERO;
						}
						BigDecimal totalPrice = dto.getTotalPrice();
						if(oConvertUtils.isEmpty(totalPrice)) {
							totalPrice = BigDecimal.ZERO;
						}
						totalPrice = totalPrice.add(price);
						dto.setTotalPrice(totalPrice.setScale(4, BigDecimal.ROUND_HALF_UP));
						if(oConvertUtils.isNotEmpty(zrkOrderProductDTO.getCreateBy())) {
							map.put(zrkOrderProductDTO.getCreateBy(), dto);
						}
					}
				}
			}
			List<ZrkOrderProductDTO> list = new LinkedList<ZrkOrderProductDTO>();
			Collection<ZrkOrderProductDTO> values =  map.values();
			Iterator<ZrkOrderProductDTO> it = values.iterator();
			while(it.hasNext()) {
				ZrkOrderProductDTO dto = it.next();
				LambdaQueryWrapper<ZrkShoporder> queryWrapper = new LambdaQueryWrapper<ZrkShoporder>();
				queryWrapper.eq(ZrkShoporder::getCreateBy, dto.getCreateBy());
				queryWrapper.between(ZrkShoporder::getOrderTime, orderTimeBegin, orderTimeEnd);
				int count = this.count(queryWrapper);
				dto.setCount(count);
				int customerCount = baseMapper.getCustomerCount(dto.getCreateBy(), orderTimeBegin, orderTimeEnd);
				dto.setCustomerCount(customerCount);
				list.add(dto);
			}
			Page<ZrkOrderProductDTO> pageList = page.setRecords(list);
			return pageList;
		}
		List<ZrkOrderProductDTO> list = new LinkedList<ZrkOrderProductDTO>();
		return page.setRecords(list);
	}


	@Override
	public  List<ZrkShoporder> getOrderByCustomerId(String  customerId){
		List<ZrkShoporder> list=zrkShoporderMapper.getOrderByCustomerId(customerId);
		return list;
	}
	@Override
	public  List<ZrkShoporder> getOrderHxYByCustomerId(String  customerId){
		List<ZrkShoporder> list=zrkShoporderMapper.getOrderHxYByCustomerId(customerId);
		return list;
	}

	@Override
	public Page<ZrkShopOrderDTO> listByModel(Page<ZrkShopOrderDTO> page, ZrkShoporder model) {
		return this.baseMapper.listByModel(page,model);
	}

	/**
	 * 校验库存是否足够
	 * @param modal 规格
	 * @param formulaId 配方id
	 * @return 是否足够
	 */
	private boolean verifyInventory(String modal,BigDecimal count,String formulaId){
		if(StringUtils.isBlank(modal)){
			throw new RuntimeException("规格信息获取失败，请检查规格格式！");
		}
		if(StringUtils.isBlank(formulaId)){
			return true;
		}
		Map<String,String> map = new HashMap<String,String>();
		String[] model = StringUtils.split(modal, "*");
		if(model.length < 2 || !isNumber(model[0]) || !isNumber(model[1])){
			throw new RuntimeException("产品规格信息获取失败，请检查格式！");
		}
		map.put("width",model[0]);
		map.put("height",model[1]);
		//产品平方
		BigDecimal square = new BigDecimal(map.get("width")).multiply(new BigDecimal(map.get("height"))).divide(new BigDecimal("100"),4,BigDecimal.ROUND_HALF_UP).multiply(count);
		//查询配方详情
		LambdaQueryWrapper<BasPfMaterial> qer = new LambdaQueryWrapper<BasPfMaterial>();
		qer.eq(BasPfMaterial::getPfid, formulaId);
		List<BasPfMaterial> pfList = pfMaterialService.list(qer);
		List<String> cateIdList = Lists.newArrayList();
		if(pfList!=null&&pfList.size()>0) {
			for(BasPfMaterial pf:pfList) {
				cateIdList.add(pf.getPfName());
			}
		}
		List<BasMaterialCategory> cateList = categoryService.listByIds(cateIdList);
		List<String> dzCateIdList = Lists.newArrayList();//临时存放底纸分类id
		List<String> mzCateIdList = Lists.newArrayList();//临时存放面纸分类id
		if(cateList!=null&&cateList.size()>0) {
			for(BasMaterialCategory cate:cateList) {
				//判断上级是底纸或面纸
				if(StringUtils.equals("1354371464532758529", cate.getPid())) {
					dzCateIdList.add(cate.getId());//底纸
				}
				if(StringUtils.equals("1354371334681300993", cate.getPid())) {
					mzCateIdList.add(cate.getId());//面纸
				}
			}
			if(dzCateIdList!=null&&dzCateIdList.size()>0) {
				for(String cateId:dzCateIdList) {
					List<StkInventory> stkList = getInventoryByCategory(cateId, "1");
					if(stkList==null || stkList.size()==0) {
						throw new RuntimeException("底纸库存不足，请补充该底纸库存");
					}
					LambdaQueryWrapper<BasProportion> lw = new LambdaQueryWrapper<BasProportion>();
					lw.eq(BasProportion::getCatagroyId, cateId);
					lw.orderByDesc(BasProportion::getCreateTime);
					List<BasProportion> proportionList = basProportionService.list(lw);
					//此处防止重复添加出错，只取最后添加的比重
					BasProportion proportion = null;
					if(proportionList!=null && proportionList.size()>0) {
						proportion = proportionList.get(0);
					}else {
						log.info("未配置比重，跳过校验底纸面纸");
						continue;
					}
					//克重
					BigDecimal g = BigDecimal.ZERO;
					//厚重
					BigDecimal t = BigDecimal.ZERO;
					//比重
					BigDecimal p = BigDecimal.ZERO;
					//计算公式
					BigDecimal gs = BigDecimal.ZERO;
					if(proportion != null) {
						//两种计算吨转平方
						//1.克重
						if(oConvertUtils.isNotEmpty(proportion.getGramWeight())) {
							g = proportion.getGramWeight()==null?BigDecimal.ZERO:proportion.getGramWeight();
							gs = g;
						}else {
							//2.比重，厚重
							t = proportion.getThickness()==null?BigDecimal.ZERO:proportion.getThickness();
							p = proportion.getProportion()==null?BigDecimal.ZERO:proportion.getProportion();
							gs = t.multiply(p);
						}
					}
					BigDecimal squareSum = BigDecimal.ZERO;
					for(StkInventory stkInventory:stkList) {
						BigDecimal w = stkInventory.getWidth()==null?BigDecimal.ZERO:stkInventory.getWidth();
						BigDecimal l = stkInventory.getLength()==null?BigDecimal.ZERO:stkInventory.getLength();
						if(StringUtils.equals("1310780214606270465", stkInventory.getUnitId())) {
							if(w.compareTo(new BigDecimal(map.get("width"))) >= 0) {
								squareSum = squareSum.add(w.multiply(l));
							}
						}
						if(StringUtils.equals("40288101710a4c6201710a6618cc0003", stkInventory.getUnitId())) {
							if(proportion==null) {
								log.info("未配置比重，跳过校验底纸面纸");
								continue;
							}
							//计算吨转平方
							BigDecimal dzSquare = stkInventory.getQty().multiply(new BigDecimal("1000000")).divide(gs,4,BigDecimal.ROUND_HALF_UP);
							squareSum = squareSum.add(dzSquare);
						}

					}
					if(squareSum.compareTo(square) < 0) {
						throw new RuntimeException("底纸库存不足，请补充该底纸库存");
					}
				}

			}
			if(mzCateIdList!=null&&mzCateIdList.size()>0) {
				for(String cateId:mzCateIdList) {
					List<StkInventory> stkList = getInventoryByCategory(cateId, "2");
					if(stkList==null || stkList.size()==0) {
						throw new RuntimeException("面纸库存不足，请补充该面纸库存");
					}
					LambdaQueryWrapper<BasProportion> lw = new LambdaQueryWrapper<BasProportion>();
					lw.eq(BasProportion::getCatagroyId, cateId);
					lw.orderByDesc(BasProportion::getCreateTime);
					List<BasProportion> proportionList = basProportionService.list(lw);
					//此处防止重复添加出错，只取最后添加的比重
					BasProportion proportion = null;
					if(proportionList!=null && proportionList.size()>0) {
						proportion = proportionList.get(0);
					}else {
						log.info("未配置比重，跳过校验底纸面纸");
						continue;
					}
					//克重
					BigDecimal g = BigDecimal.ZERO;
					//厚重
					BigDecimal t = BigDecimal.ZERO;
					//比重
					BigDecimal p = BigDecimal.ZERO;
					//计算公式
					BigDecimal gs = BigDecimal.ZERO;
					if(proportion != null) {
						//两种计算吨转平方
						//1.克重
						if(oConvertUtils.isNotEmpty(proportion.getGramWeight())) {
							g = proportion.getGramWeight()==null?BigDecimal.ZERO:proportion.getGramWeight();
							gs = g;
						}else {
							//2.比重，厚重
							t = proportion.getThickness()==null?BigDecimal.ZERO:proportion.getThickness();
							p = proportion.getProportion()==null?BigDecimal.ZERO:proportion.getProportion();
							gs = t.multiply(p);
						}
					}
					BigDecimal squareSum = BigDecimal.ZERO;
					for(StkInventory stkInventory:stkList) {
						BigDecimal w = stkInventory.getWidth()==null?BigDecimal.ZERO:stkInventory.getWidth();
						BigDecimal l = stkInventory.getLength()==null?BigDecimal.ZERO:stkInventory.getLength();
						if(StringUtils.equals("1310780214606270465", stkInventory.getUnitId())) {
							if(w.compareTo(new BigDecimal(map.get("width"))) >= 0) {
								squareSum = squareSum.add(w.multiply(l));
							}
						}
						if(StringUtils.equals("40288101710a4c6201710a6618cc0003", stkInventory.getUnitId())) {
							if(proportion==null) {
								log.info("未配置比重，跳过校验底纸面纸");
								continue;
							}
							//计算吨转平方
							BigDecimal dzSquare = stkInventory.getQty().multiply(new BigDecimal("1000000")).divide(gs,4,BigDecimal.ROUND_HALF_UP);
							squareSum = squareSum.add(dzSquare);
						}
					}
					if(squareSum.compareTo(square) < 0) {
						throw new RuntimeException("面纸库存不足，请补充该面纸库存");
					}
				}
			}
		}
		return true;
	}

	@Override
	@Transactional(rollbackFor= Exception.class)
	public Result<?> createZzOrder(CreateZzOrderVO createZzOrderVO) {
		if(createZzOrderVO.getIds() != null && createZzOrderVO.getIds().length > 0){
			for(String orderId:createZzOrderVO.getIds()){
				ZrkShoporder zso=zrkShoporderMapper.selectById(orderId);
				if(StringUtils.equals(zso.getIsPush(),"1")){
					return Result.error("所选销售单中包含已生成任务单的订单:"+zso.getOrderNo()+",不能重复生成");
				}
				ZrkOrderProduct zop = zrkOrderProductMapper.selectById(orderId);
				Date date = DateUtils.getDate();
				Long dateNum = date.getTime();
				if(zop == null){
					return Result.error("销售单号："+zso.getOrderNo()+",获取销售信息失败");
				}
				ZzShoporder zsd=new ZzShoporder();
				zsd.setOrderProdect(zop.getId());
				zsd.setIsPush(0);
				zsd.setProcessId(zop.getProcessId());
				zsd.setOrderName("系统分派任务工单");
				zsd.setOrderNo(zso.getOrderNo());
				zsd.setSpecs(zop.getProductSpecs());//规格
				if(oConvertUtils.isEmpty(zop.getJsId())) {
					zsd.setGlue("");
				}else {
					zsd.setGlue(zop.getJsId());
				}
				String workNo = StringUtils.EMPTY;
				Boolean flag = true;
				String processId = zop.getProcessId();
				ZzDeviceType process = zzDeviceTypeMapper.selectById(processId);
				if(null != process) {
					String processName = process.getDeviceTpyeName();
					if(StringUtils.isNotBlank(processName) && processName.contains("复合")) {
						workNo = iSysBaseAPI.getNoByCode("work_fh_no");
						flag = false;
					}
					if(StringUtils.isNotBlank(processName) && processName.contains("分切")) {
						workNo = iSysBaseAPI.getNoByCode("work_fq_no");
						flag = false;
					}
					if(StringUtils.isNotBlank(processName) && processName.contains("切张")) {
						workNo = iSysBaseAPI.getNoByCode("work_qz_no");
						flag = false;
					}
					if(StringUtils.isNotBlank(processName) && processName.contains("制胶")) {
						workNo = iSysBaseAPI.getNoByCode("work_zj_no");
						flag = false;
					}
				}
				if(flag) {
					workNo = iSysBaseAPI.getNoByCode("work_no");
				}

				zsd.setWoCode(workNo);
				zsd.setWoPlanstarttime(zso.getCreateTime());
				zsd.setWoPlanendtime(createZzOrderVO.getCreateTime());
				zsd.setCategoryId(zop.getMaterialId());
				zsd.setWoDeliverytime(createZzOrderVO.getUpdateTime());
				zsd.setWoPartcode(iSysBaseAPI.getNoByCode("productNO"));
				zsd.setWoPartname(zop.getProductName());
				if(null != zop.getProductCount()) {
					zsd.setWoQuantity(zop.getProductCount().intValue());
				} else {
					zsd.setWoQuantity(null);
				}
				zsd.setWoType("1");
				zsd.setWoPriority(2);
				zsd.setWoStatus(1);
				zsd.setFacialSupplier(zop.getMzId());
				zsd.setGlueSupplier(zop.getJsId());
				zsd.setPaperSupplier(zop.getMzId());
				BasCustomer bc = basCustomerMapper.selectById(zso.getCustomerId());
				if(bc != null){
					zsd.setCustomerName(bc.getName());
				}
				String formulaId = zop.getFormularId();
				String sdf = null;
				if(StringUtils.isNotBlank(formulaId)) {
					zsd.setFormulaId(zop.getFormularId());
					LambdaQueryWrapper<BasPfMaterial> query = new LambdaQueryWrapper<>();
					query.eq(BasPfMaterial::getPfid, formulaId);
					List<BasPfMaterial> list = pfMaterialService.list(query);
					sdf = "原料名称：";
					for (BasPfMaterial pf : list) {
						String categoryId = pf.getPfName();
						BasMaterialCategory category = basMaterialCategoryMapper.selectById(categoryId);
						sdf += category.getName() + " " + category.getCode() + ",";
					}
					sdf = sdf.substring(0, sdf.length()-1);
				}
				String remark = zop.getRemark();//获取总订单的
				if(null == remark) {
					zsd.setRemark(sdf);
				}
				else {
					if(sdf != null) {
						zsd.setRemark(remark + "," + sdf);
					} else {
						zsd.setRemark(remark);
					}
				}
				zsd.setRemark(remark);
				zzShoporderMapper.insert(zsd);
				//将销售订单置为已生成任务工单
				zso.setIsPush("1");
				zrkShoporderMapper.updateById(zso);
				iSysBaseAPI.sendMessage(zso.getId());
			}
		}
		return Result.ok("生成车间任务单成功");
	}

	@Override
	public boolean updateCreateBy(ZrkShoporder zrkShoporder) {
		// TODO Auto-generated method stub
		if(StringUtils.isBlank(zrkShoporder.getId())) {
			throw new RuntimeException("未找到当前销售订单信息");
		}
		//根据订单id查询订单信息
//		ZrkShoporder shoporder = this.getById(zrkShoporder.getId());
//		if(shoporder == null) {
//			throw new RuntimeException("未找到当前销售订单信息");
//		}
//		shoporder.setCreateBy(zrkShoporder.getCreateBy());
		return this.updateById(zrkShoporder);
	}
}
